import Cache from "../../utils/cache";
import {
	LOGIN_STATUS,
	UID,
	USER_INFO,
	USER_TYPE,
	IS_STORE,
	BG_USER_TYPE,
	IS_SALESMAN
} from "../../config/cache";


const state = {
	token: Cache.get(LOGIN_STATUS) || null,
	userInfo: {},
	uid: Cache.get(UID) || null,
	userType: Cache.get(USER_TYPE) || null,
	isStore: Cache.get(IS_STORE) || null,
	bgUserType: Cache.get(BG_USER_TYPE) || null,
	isSalesman: Cache.get(IS_SALESMAN) || null,
};

const mutations = {
	LOGIN(state, opt) {
		state.token = opt.token;
		Cache.set(LOGIN_STATUS, opt.token, opt.time);
	},
	SETUID(state, val) {
		state.uid = val;
		Cache.set(UID, val);
	},
	UPDATE_LOGIN(state, token) {
		state.token = token;
	},
	LOGOUT(state) {
		state.token = undefined;
		state.uid = undefined;
		Cache.clear(LOGIN_STATUS);
		Cache.clear(UID);
	},
	UPDATE_USERINFO(state, userInfo) {
		state.userInfo = userInfo;
		Cache.set(USER_INFO, userInfo);
	},
	USER_TYPE(state, val) {
		state.userType = val;
		Cache.set(USER_TYPE, val);
	},
	IS_STORE(state, val) {
		state.isStore = val;
		Cache.set(IS_STORE, val);
	},
	IS_SALE(state, val) {
		state.bgUserType = val;
		Cache.set(BG_USER_TYPE, val);
	},
	IS_SALESMAN(state, value) {
		state.isSalesman = value;
		Cache.set(IS_SALESMAN, value);
	}
};

const actions = {
	USERINFO({
		state,
		commit
	}, force) {
		if (state.userInfo !== null && !force) {
			return Promise.resolve(state.userInfo);
		} else {
			return new Promise(reslove => {
				this.$request.get('user/getUserInfo', {
					userInfoId: state.uid
				}).then(res => {
					console.log(res);
					commit("UPDATE_USERINFO", res.data);
					Cache.set(USER_INFO, res.data);
					reslove(res.data);
				})
			})
		}
	}
};

export default {
	state,
	mutations,
	actions
};